package com.jrx.anytxn.transaction.job.customer.config;

import com.jrx.anytxn.common.constant.Constants;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.entity.CmCustomerLimitInfo;
import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrCodeTableMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.job.customer.step.LimitRenewalProcessor;
import com.jrx.anytxn.transaction.job.customer.step.LimitRenewalWriter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @comment: 额度续期任务定义
 * @author: liuzb
 * @date: 2022/10/19 10:00
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
@EnableBatchProcessing
public class LimitRenewalJobConfiguration {

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    AnytxnBatchProperties anytxnBatchProperties;
    @Autowired
    LimitRenewalProcessor limitRenewalProcessor;
    @Autowired
    LimitRenewalWriter limitRenewalWriter;
    @Autowired
    PlatformTransactionManager platformTransactionManager;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtPrCodeTableMapper extPrCodeTableMapper;

    @Bean
    public Job limitRenewalJob() {
        return jobBuilderFactory.get("limitRenewalJob")
                .incrementer(new RunIdIncrementer())
                // 预先跑风控
                .start(limitRenewalStep())
                .build();
    }


    /*************预先跑风控*************/
    @Bean
    public Step limitRenewalStep() {
        return stepBuilderFactory.get("limitRenewalStep")
                .<CmCustomerLimitInfo, CmCustomerLimitInfo>chunk(anytxnBatchProperties.getDefaultConfig().getChunkLimit())
                .reader(limitRenewalReader())
                .processor(limitRenewalProcessor)
                .writer(limitRenewalWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getDefaultConfig().getThrottleLimit())
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<CmCustomerLimitInfo> limitRenewalReader() {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        // 当前业务日期
        Date today = org.getNextProcessingDate();
        // 获取额度续期发送天数的设置
        List<PrCodeTable> prCodeTables = extPrCodeTableMapper.selectAllByTypeIdAndTenId("RENEWAL_DAY", org.getTenantId());
        PrCodeTable prCodeTable = prCodeTables.get(0);
        String day = prCodeTable.getCodeDescription();
        // 提前30天跑风控
        Date date = DateUtils.addDay(today, Integer.parseInt(day));
        MyBatisCursorItemReader<CmCustomerLimitInfo> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerLimitInfoMapper.selectLimitRenewalCus");
        //查询参数设置
        Map<String, Object> map = new HashMap<>();
        map.put("beginDay", DateUtils.format(today));
        map.put("endDay", DateUtils.format(date));
        map.put("tenantId", Constants.DEFAULT_TENANT_ID);
        map.put("status", CustomerConstant.STATUS_NORMAL);
        cursorItemReader.setParameterValues(map);
        SynchronizedItemStreamReader<CmCustomerLimitInfo> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }
}
